import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'
import 'element-ui/lib/theme-chalk/index.css'
import { initMenu } from './utils/menus'

import 'font-awesome/css/font-awesome.css'

//组件形式引入
import {postRequest} from './utils/api'
import {putRequest} from './utils/api'
import {getRequest} from './utils/api.js'
import {deleteRequest} from './utils/api'

axios.defaults.withCredentials = true

axios.create({
  baseURL: '/',
  withCredentials: true,
  timeout: 5000
})

//vuex
import store from './store'

import ElementUI from 'element-ui'

Vue.config.productionTip = true//控制台的提示
Vue.use(ElementUI, {size:'small'})//默认size small

//插件形式使用请求
Vue.prototype.postRequest = postRequest
Vue.prototype.putRequest = putRequest
Vue.prototype.getRequest = getRequest
Vue.prototype.deleteRequest = deleteRequest

router.beforeEach((to, from, next) => {//路由守卫, 回退之后, 路径会回到from
  //在路由守卫中 判断用户是否登录
  if(window.sessionStorage.getItem('tokenStr')){//通过token判断用户是否登录
    initMenu(router, store)//有登录就更新路由

    if(!window.sessionStorage.getItem('user')){//判断内存里用户信息是否存在
      return getRequest('/admin/info').then(res => {//不存再就请求信息
        if(res){
          window.sessionStorage.setItem('user', JSON.stringify(res))//存储用户信息
          store.commit('INIT_CURRENTAdmin', res)
          next()
        }
      })
    }
    next()
  }else{
    if(to.path ===  '/'){
      next()
    }//如果没登录,但是to的刚好是登录页,就直接让他进行跳转
    else{
      next('/?redirect=' + to.path)//如果不是的话,就重定向,记录to.path,拿到login页面去判断
      //这里的写法是/  后面跟着参数  /就是login的路由,所以这里其实相当于 /login?redirect=path,通过后面的参数把路径传递到login去了
    }
  }
  }
)

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
